#include "StdAfx.h"
#include "FlowPool.h"
#include <vector>
#include "TinyServerDefine.h"

namespace IVRFlow
{

	CFlowPool::CFlowPool(void)
	{
		//init flows
		std::vector<IVRFlow::CFlowConfig*>* flows = g_TinyCCDBMgr.flows->GetAll();
		for(int i = 0; i<flows->size();++i)
		{
			m_flowConfigs.insert(std::pair<std::string,IVRFlow::CFlowConfig*>(flows->at(i)->MatchPrefix,flows->at(i)));
		}
		delete flows;
	}

	CFlowPool::~CFlowPool(void)
	{
	}

	bool CFlowPool::StartFlow(std::string callerID, std::string calledID, std::string talkID)
	{
		//start 0 flow temp
		if(m_flowConfigs.find(talkID) == m_flowConfigs.end())
		{
			CTalkFlow * tmpFlow = getNewFlow(talkID);
			tmpFlow->flowConfig = m_flowConfigs[0];
			tmpFlow->StartFlow(talkID);
		}
		else
		{
			g_Logger.log(debug1,"start Flow error, talkID exist in current flow pool!");
		}

		return true;
	}


	CTalkFlow* CFlowPool::getNewFlow(std::string talkID)
	{
		CTalkFlow* tmpTalk = new CTalkFlow();
		tmpTalk->TalkID = talkID;
		m_flows.insert(std::pair<std::string, CTalkFlow*>(talkID,tmpTalk));
		return tmpTalk;
	}

	CTalkFlow* CFlowPool::getFlowByTalkID(std::string talkID)
	{
		return m_flows[talkID];
	}

	


	void CFlowPool::ProcessReceivedMsg(CTinyMsg& inMsg,CTinyMsg& OutMsg)
	{
		if(inMsg.getMsgIndex() == VOICECARD_ACTION)
		{
			switch (inMsg.getMsgItem())
			{
			case VOICECARD_ALERT:
				{
					//everytime, get talkobject and then invoke flow to process
					CTalkFlow* flow = getFlowByTalkID("");
					flow->ProcessReceivedMsg(inMsg, OutMsg);

				}break;
			default:
				break;
			}
		}
	}

}